package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"time"
	// "github.com/EDDYCJY/gsema"
)

// var sema = gsema.NewSemaphore(20)
func DirSizeMB(path string) float64 {
	// defer sema.Done()
	// sema.Add(1)
	sizes := make(chan int64)
	readSize := func(path string, file os.FileInfo, err error) error {
		if err != nil || file == nil {
			return nil // Ignore errors
		}
		if !file.IsDir() {
			sizes <- file.Size()
		}
		return nil
	}

	go func() {
		_ = filepath.Walk(path, readSize)
		close(sizes)
	}()

	size := int64(0)
	for s := range sizes {
		size += s
	}

	sizeMB := float64(size) / 1024.0 / 1024.0

	fmt.Println(path, " ", sizeMB, "MB")
	return sizeMB
}
func main() {
	var BasePath string
	flag.StringVar(&BasePath, "p", "C:\\", "用户名,默认为空")
	flag.Parse()
	//size := DirSizeMB("c:\\")
	//fmt.Println(size, "MB")
	t1 := time.Now()

	fmt.Println(t1.String())
	_ = filepath.Walk(BasePath, func(path string, file os.FileInfo, err error) error {
		if file.IsDir() {
			path2 := strings.Replace(path, BasePath, "", -1)
			n := strings.Count(path2, "\\")
			//fmt.Println(n)
			if n < 2 {
				go DirSizeMB(path)

			}

		}

		return nil
	})
	// sema.Wait()
	elapsed := time.Since(t1)
	fmt.Println("App elapsed: ", elapsed)
}
